package com.unicdata.ai.demo_2af.common.exception;

import com.unicdata.ai.demo_2af.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 异常处理
 *
 * @author lhn
 * @date 2025/06/25 16:43
 * @since 1.0.0
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Shiro认证异常
     */
    //@ExceptionHandler(AuthenticationException.class)
    //public Result<Void> handleAuthenticationException(AuthenticationException e) {
    //    log.error("认证异常: {}", e.getMessage());
    //
    //    if (e instanceof UnknownAccountException) {
    //        return Result.error("账号不存在");
    //    } else if (e instanceof IncorrectCredentialsException) {
    //        return Result.error("密码错误");
    //    } else if (e instanceof LockedAccountException) {
    //        return Result.error("账号已被锁定,请联系管理员");
    //    }
    //    return Result.error("认证失败");
    //}

    /**
     * 处理Shiro授权异常
     */
    @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
    public Result<Void> handleAuthorizationException() {
        return Result.error("没有权限执行此操作", 403);
    }

    /**
     * 处理Shiro未认证异常
     */
    @ExceptionHandler(UnauthenticatedException.class)
    public Result<Void> handleUnauthenticatedException() {
        return Result.error("未登录或登录已过期", 401);
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        log.error(msg);
        return Result.error(msg, 400);
    }

    /**
     * 处理参数绑定异常
     */
    //@ExceptionHandler(BindException.class)
    //public Result<Void> handleBindException(BindException e) {
    //    BindingResult bindingResult = e.getBindingResult();
    //    StringBuilder sb = new StringBuilder("参数绑定失败:");
    //    for (FieldError fieldError : bindingResult.getFieldErrors()) {
    //        sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
    //    }
    //    String msg = sb.toString();
    //    log.error(msg);
    //    return Result.error(msg, 400);
    //}

    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
        Set <ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder("参数验证失败:");
        for (ConstraintViolation <?> violation : violations) {
            sb.append(violation.getMessage()).append(", ");
        }
        String msg = sb.toString();
        log.error(msg);
        return Result.error(msg, 400);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 处理所有未捕获异常
     */
    @ExceptionHandler(Exception.class)
    public Result <Void> handleException(Exception e) {
        log.error("系统异常: ", e);
        return Result.error("系统错误,请联系管理员");
    }
}